import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:ytbusiness/config/style.dart';
import 'package:ytbusiness/config/yt_theme.dart';
import 'package:ytbusiness/state/user_role.dart';
import 'package:ytbusiness/utils/helper.dart';
import 'package:ytbusiness/utils/screen_adaptation.dart';
import 'package:ytbusiness/utils/sp_util.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:io';
import 'package:jverify/jverify.dart';
import 'package:ytbusiness/config/config.dart';

//选择角色
class CheckRole extends StatefulWidget {
  @override
  _CheckRoleState createState() => _CheckRoleState();
}

class _CheckRoleState extends State<CheckRole> {
  //login_logo.png
  /// 统一 key
  final String f_result_key = "result";

  /// 错误码
  final String f_code_key = "code";

  /// 回调的提示信息，统一返回 flutter 为 message
  final String f_msg_key = "message";

  /// 运营商信息
  final String f_opr_key = "operator";
  String _platformVersion = 'Unknown';
  String _result = "token=";
  var controllerPHone = TextEditingController();
  final Jverify jverify = Jverify();
  bool _loading = false; //防止重复点击
  String _token;

  List<String> _roleList = ["修理厂", "汽配商", "勘察员"];
  List<String> _titleList = ["修理厂", "汽配商", "保险"];
  bool isChoose = true; //选中
  int selectRole = 1; //选中角色
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initPlatformState();
    setState(() {
      if (Provider.of<UserRole>(context, listen: false).role == null) {
        selectRole = 1;
      } else {
        selectRole = Provider.of<UserRole>(context, listen: false).role;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AbsorbPointer(
      absorbing: _loading,
      child: Scaffold(
        backgroundColor: Colors.white,
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          actions: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    _bottomSheet(context);
                  },
                  child: Container(
                    margin:
                        EdgeInsets.only(right: setWidth(20), top: setWidth(30)),
                    child: Text(
                      '选择角色',
                      style: TextStyle(
                        color: Color(0xff1A79FF),
                        fontSize: setSp(14),
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
        body: Stack(
          children: [
            Container(),
            SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(
                  top: setWidth(53),
                ),
                width: ScreenUtil.screenWidthDp,
                child: Column(
                  children: <Widget>[
                    Row(
                      children: [
                        SizedBox(
                          width: setWidth(27),
                        ),
                        Image.asset(
                          'assets/images/login_logo.png',
                          width: setWidth(166),
                          height: setWidth(52),
                          fit: BoxFit.cover,
                        ),
                      ],
                    ),
                    SizedBox(
                      height: setWidth(30),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: setWidth(30),
                        ),
                        Text(
                          '${_titleList[selectRole - 1]}协同管理系统',
                          style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: setSp(26),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        SizedBox(
                          height: setWidth(269),
                        ),
                        Padding(
                          padding: EdgeInsets.only(
                            left: setWidth(40),
                            right: setWidth(40),
                          ),
                          child: InkWell(
                            onTap: () {
                              if (!isChoose) {
                                toast("请阅读并同意《云途养护用户协议》");
                                return;
                              }
                              switch (selectRole) {
                                case 1:
                                  urlPush(context, "yuntu://create_store");
                                  break;
                                case 2:
                                  urlPush(context, "yuntu://create_store");
                                  break;
                                case 3:
                                  urlPush(context, "yuntu://scout_login");
                                  break;
                              }
                            },
                            child: Container(
                              width: setWidth(295),
                              height: setWidth(40),
                              decoration: BoxDecoration(
                                color: Color(0xff08BB07),
                                borderRadius:
                                    BorderRadius.circular(setWidth(4)),
                              ),
                              alignment: Alignment.center,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Image.asset(
                                    'assets/images/weChatWhite_image.png',
                                    width: setWidth(21),
                                    height: setWidth(17),
                                    fit: BoxFit.fill,
                                  ),
                                  SizedBox(
                                    width: setWidth(10),
                                  ),
                                  Text(
                                    '微信登录',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: setSp(15),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                        SizedBox(
                          height: setWidth(32),
                        ),

                        //其他方式登录
                        GestureDetector(
                          onTap: () {
                            if (!isChoose) {
                              toast("请阅读并同意《云途养护用户协议》");
                              return;
                            }

                            switch (selectRole) {
                              case 1:
                                loginAuth();
                                break;
                              case 2:
                                loginAuth();
                                break;
                              case 3:
                                urlPush(context, "yuntu://scout_login");
                                break;
                            }
                          },
                          child: Text(
                            "其他登录方式",
                            style: TextStyle(
                              color: Colors.black54,
                              fontSize: setSp(13),
                            ),
                          ),
                        ),
                        SizedBox(
                          height: setWidth(6),
                        ),
                        Image.asset(
                          'assets/images/downGrey_image.png',
                          width: setWidth(12),
                          height: setWidth(5),
                          fit: BoxFit.fill,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
              bottom: setWidth(30),
              child: _buildBottom(context),
            ),
          ],
        ),
      ),
    );
  }

  //协议条款
  Widget _buildBottom(BuildContext context) {
    return Container(
      width: setWidth(375),
      alignment: Alignment.center,
      child: Center(
        child: RichText(
          text: TextSpan(
            children: [
              WidgetSpan(
                alignment: PlaceholderAlignment.middle,
                child: InkWell(
                  onTap: () {
                    setState(() {
                      isChoose = !isChoose;
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: setWidth(5),
                      vertical: setWidth(5),
                    ),
                    child: Icon(
                      isChoose
                          ? Icons.check_circle
                          : Icons.radio_button_unchecked,
                      size: setWidth(17),
                      color: isChoose ? Color(0xff08BB07) : Color(0xffa4a5a9),
                    ),
                  ),
                ),
              ),
              TextSpan(
                text: "我已阅读并同意",
                style: TextStyle(
                  fontSize: setSp(13),
                  color: Color(0xff989898),
                ),
              ),
              TextSpan(
                text: "《云途养护用户协议》",
                style: TextStyle(
                  fontSize: setSp(13),
                  color: Color(0xff08BB07),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  //底部弹窗
  _bottomSheet(BuildContext context) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (BuildContext context, StateSetter state) {
              return ListView.builder(
                  itemCount: 3,
                  shrinkWrap: true,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          SPUtil.remove("role");
                          SPUtil.setInt("role", index + 1);
                          print(index + 1);
                          Provider.of<UserRole>(context, listen: false)
                              .upDateUserRole(index + 1);
                          switch (index) {
                            case 0:
                              YTTheme.getInstance()
                                ..color = YTStyle.mainColor
                                ..init();
                              break;
                            case 1:
                              YTTheme.getInstance()
                                ..color = YTStyle.autoMakers
                                ..init();
                              break;
                            case 2:
                              YTTheme.getInstance()
                                ..color = Color(0xff00D5FF)
                                ..init();
                              break;
                          }
                          setState(() {
                            selectRole = index + 1;
                          });
                          Navigator.pop(context);
                        },
                        child: _listItem(roleName: _roleList[index]));
                  });
            },
          );
        });
  }

  //角色列表
  Widget _listItem({String roleName}) {
    return Container(
      padding: EdgeInsets.only(
        top: setWidth(22),
        bottom: setWidth(22),
      ),
      margin: EdgeInsets.only(left: setWidth(10), right: setWidth(10)),
      decoration: BoxDecoration(
          border: Border(
              bottom:
                  BorderSide(color: Color(0xffF0F0F0), width: setWidth(0.5)))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            child: Text(
              roleName,
              style: TextStyle(color: Color(0xff333333), fontSize: setSp(16)),
            ),
          ),
        ],
      ),
    );
  }

  // 初始化一键登录
  Future<void> initPlatformState() async {
    String platformVersion;

    // 初始化 SDK 之前添加监听
    jverify.addSDKSetupCallBackListener((JVSDKSetupEvent event) {
      print("receive sdk setup call back event :${event.toMap()}");
    });

    jverify.setDebugMode(false); // 打开调试模式
    jverify.setup(
        appKey: Config.jpAppKey, //"你自己应用的 AppKey",
        channel: "devloper-default"); // 初始化sdk,  appKey 和 channel 只对ios设置有效

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });

    /// 授权页面点击事件监听
    jverify.addAuthPageEventListener((JVAuthPageEvent event) {
      print("receive auth page event :${event.toMap()}");
    });

    _preLogin();
  }

  ///预取号操作
  _preLogin() {
    jverify.preLogin().then((map) {
      int code = map[f_code_key] as int;
      String message = map[f_msg_key] as String;
      setState(() {
        _result = "[$code] message = $message";
      });
    });
  }

  /// SDK 请求授权一键登录
  void loginAuth() {
    setState(() {
      _loading = true;
    });
    jverify.checkVerifyEnable().then((map) {
      bool result = map[f_result_key] as bool;
      if (result) {
        final screenSize = MediaQuery.of(context).size;
        final screenWidth = screenSize.width;
        final screenHeight = screenSize.height;
        bool isiOS = Platform.isIOS;

        /// 自定义授权的 UI 界面，以下设置的图片必须添加到资源文件里，
        /// android项目将图片存放至drawable文件夹下，可使用图片选择器的文件名,
        /// 例如：btn_login.xml,入参为"btn_login"。
        /// ios项目存放在 Assets.xcassets。

        ///配置登录界面
        JVUIConfig uiConfig = JVUIConfig();
        //uiConfig.authBackgroundImage = ;

        //uiConfig.navHidden = true;
        uiConfig.navColor = 0xffFFFFFF;
        uiConfig.navText = "登录";
        uiConfig.navTextColor = 0xff333333;
        uiConfig.navReturnImgPath = "return"; //图片必须存在

        uiConfig.logoWidth = 84;
        uiConfig.logoHeight = 84;
        //uiConfig.logoOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.logoWidth/2).toInt();
        uiConfig.logoOffsetY = 100;
        uiConfig.logoVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        uiConfig.logoHidden = false;
        uiConfig.logoImgPath = "logo";

        uiConfig.numberFieldWidth = 200;
        uiConfig.numberFieldHeight = 40;
        //uiConfig.numFieldOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.numberFieldWidth/2).toInt();
        uiConfig.numFieldOffsetY = isiOS ? 100 : 200;
        uiConfig.numberVerticalLayoutItem = JVIOSLayoutItem.ItemLogo;
        uiConfig.numberColor = YTTheme.theme.value;
        uiConfig.numberSize = 18;

        uiConfig.sloganOffsetY = isiOS ? 100 : 240;
        uiConfig.sloganVerticalLayoutItem = JVIOSLayoutItem.ItemNumber;
        uiConfig.sloganTextColor = Colors.black.value;
        uiConfig.sloganTextSize = 15;
//        uiConfig.slogan
        //uiConfig.sloganHidden = 0;

        uiConfig.logBtnWidth = 250;
        uiConfig.logBtnHeight = 50;
        //uiConfig.logBtnOffsetX = isiOS ? 0 : null;//(screenWidth/2 - uiConfig.logBtnWidth/2).toInt();
        uiConfig.logBtnOffsetY = isiOS ? 100 : 310;
        uiConfig.logBtnVerticalLayoutItem = JVIOSLayoutItem.ItemSlogan;
        uiConfig.logBtnText = "一键登录";
        uiConfig.logBtnTextColor = Colors.white.value;
        uiConfig.logBtnTextSize = 16;
        uiConfig.loginBtnNormalImage = "login_btn_normal"; //图片必须存在
        uiConfig.loginBtnPressedImage = "login_btn_press"; //图片必须存在
        uiConfig.loginBtnUnableImage = "login_btn_unable"; //图片必须存在

        uiConfig.privacyHintToast =
            true; //only android 设置隐私条款不选中时点击登录按钮默认显示toast。

        uiConfig.privacyState = true; //设置默认勾选
        uiConfig.privacyCheckboxSize = 15;
        uiConfig.checkedImgPath = "check_image"; //图片必须存在
        uiConfig.uncheckedImgPath = "uncheck_image"; //图片必须存在
        uiConfig.privacyCheckboxInCenter = true;
        //uiConfig.privacyCheckboxHidden = false;

        // uiConfig.privacyOffsetX =
        //     isiOS ? (20 + uiConfig.privacyCheckboxSize) : null;
        uiConfig.privacyOffsetY = 15; // 距离底部距离
        uiConfig.privacyVerticalLayoutItem = JVIOSLayoutItem.ItemSuper;
        // uiConfig.clauseName = "《云途养护用户协议》";
        uiConfig.clauseUrl = "http://www.baidu.com";
        uiConfig.clauseBaseColor = Colors.black.value;
        uiConfig.clauseColor = YTTheme.theme.value;
        uiConfig.privacyText = ["我已阅读"];
        uiConfig.privacyTextSize = 13;
        //uiConfig.privacyWithBookTitleMark = true;
        //uiConfig.privacyTextCenterGravity = false;
        uiConfig.authStatusBarStyle = JVIOSBarStyle.StatusBarStyleDarkContent;
        uiConfig.privacyStatusBarStyle = JVIOSBarStyle.StatusBarStyleDefault;
        uiConfig.modelTransitionStyle =
            JVIOSUIModalTransitionStyle.CrossDissolve;

        uiConfig.statusBarColorWithNav = true;
        uiConfig.virtualButtonTransparent = true;

        uiConfig.privacyStatusBarColorWithNav = true;
        uiConfig.privacyVirtualButtonTransparent = true;

        uiConfig.needStartAnim = true;
        uiConfig.needCloseAnim = true;

        uiConfig.privacyNavColor = Colors.white.value;
        uiConfig.privacyNavTitleTextColor = Colors.black.value;
        uiConfig.privacyNavTitleTextSize = 16;

        uiConfig.privacyNavTitleTitle = "ios lai le"; //only ios
        uiConfig.privacyNavTitleTitle1 = "云途养护用户协议";
        uiConfig.privacyNavTitleTitle2 = "协议22 web页标题";
        uiConfig.privacyNavReturnBtnImage = "return"; //图片必须存在;

        /// 添加自定义的 控件 到授权界面
        List<JVCustomWidget> widgetList = [];

        /// 步骤 1：调用接口设置 UI
        jverify.setCustomAuthorizationView(true, uiConfig,
            landscapeConfig: uiConfig, widgets: widgetList);

        /// 步骤 2：调用一键登录接口
        /// 先，添加 loginAuthSyncApi 接口回调的监听
        jverify.addLoginAuthCallBackListener((event) {
          setState(() {
            _loading = false;
            _result = "监听获取返回数据：[${event.code}] message = ${event.message}";
            print("loginToken===========================>${event.message}");
          });
          print(
              "通过添加监听，获取到 loginAuthSyncApi 接口返回数据，code=${event.code},message = ${event.message},operator = ${event.operator}");

          if (event.code == 6001) {
            toast("请切换至手机数据连接尝试一键登录");
            return;
          }

          if (event.code == 6002) {
            print("取消一键登录");
            return;
          }

          if (event.code != 6000) {
            urlPush(context, "yuntu://one_click_login");
            print("当前网络环境不支持一键登录");
          } else {}
        });

        /// 再，执行同步的一键登录接口
        jverify.loginAuthSyncApi(autoDismiss: true);
      } else {
        setState(() {
          _loading = false;
        });

        ///当前环境不能一键登录跳转到短信验证码登录
        urlPush(context, "yuntu://one_click_login");
      }
    });
  }
}
